<template>
  <div class="project-detail">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <div v-else-if="!project" class="empty-state">
      <el-empty description="项目不存在" />
    </div>

    <div v-else>
      <!-- 项目头部信息 -->
      <el-card class="project-header-card">
        <div class="project-header">
          <div class="header-left">
            <h1>{{ project.name }}</h1>
            <p>{{ project.description || "暂无描述" }}</p>
            <div class="project-meta">
              <el-tag :type="getStatusType(project.status)">
                {{ getStatusText(project.status) }}
              </el-tag>
              <span class="meta-item">
                <el-icon><Calendar /></el-icon>
                {{ formatDate(project.startDate) }} -
                {{ formatDate(project.endDate) }}
              </span>
              <span class="meta-item">
                <el-icon><User /></el-icon>
                {{ project.members?.length || 0 }} 名成员
              </span>
            </div>
          </div>

          <div class="header-right">
            <el-button-group>
              <el-button @click="$router.push(`/projects/${project.id}/board`)">
                <el-icon><Grid /></el-icon>
                看板视图
              </el-button>
              <el-button @click="$router.push(`/projects/${project.id}/docs`)">
                <el-icon><Document /></el-icon>
                文档管理
              </el-button>
              <el-button
                @click="$router.push(`/projects/${project.id}/members`)"
              >
                <el-icon><User /></el-icon>
                成员管理
              </el-button>
              <el-button @click="showEditDialog = true">
                <el-icon><Edit /></el-icon>
                编辑项目
              </el-button>
            </el-button-group>
          </div>
        </div>
      </el-card>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧：任务相关 -->
        <div class="left-content">
          <!-- 任务统计 -->
          <el-card class="stats-card">
            <template #header>
              <div class="card-header">
                <span>任务统计</span>
                <el-button type="primary" @click="showCreateTaskDialog = true">
                  <el-icon><Plus /></el-icon>
                  新建任务
                </el-button>
              </div>
            </template>

            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-icon total">
                  <el-icon><List /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ stats.totalTasks }}</div>
                  <div class="stat-label">总任务数</div>
                </div>
              </div>

              <div class="stat-item">
                <div class="stat-icon completed">
                  <el-icon><Check /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ stats.completedTasks }}</div>
                  <div class="stat-label">已完成</div>
                </div>
              </div>

              <div class="stat-item">
                <div class="stat-icon pending">
                  <el-icon><Clock /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ stats.pendingTasks }}</div>
                  <div class="stat-label">进行中</div>
                </div>
              </div>

              <div class="stat-item">
                <div class="stat-icon overdue">
                  <el-icon><Warning /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ stats.overdueTasks }}</div>
                  <div class="stat-label">已逾期</div>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 任务列表 -->
          <el-card class="tasks-card">
            <template #header>
              <div class="card-header">
                <span>任务列表</span>
                <div class="header-actions">
                  <el-input
                    v-model="taskSearchKeyword"
                    placeholder="搜索任务..."
                    style="width: 200px; margin-right: 8px"
                    clearable
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                  <el-select
                    v-model="taskStatusFilter"
                    placeholder="状态筛选"
                    style="width: 120px; margin-right: 8px"
                    clearable
                  >
                    <el-option label="全部" value="" />
                    <el-option label="进行中" :value="0" />
                    <el-option label="已完成" :value="1" />
                  </el-select>
                </div>
              </div>
            </template>

            <div v-if="tasksLoading" class="loading-container">
              <el-skeleton :rows="5" animated />
            </div>

            <div v-else-if="filteredTasks.length === 0" class="empty-state">
              <el-empty description="暂无任务">
                <el-button type="primary" @click="showCreateTaskDialog = true">
                  创建第一个任务
                </el-button>
              </el-empty>
            </div>

            <div v-else class="task-list">
              <div
                v-for="task in filteredTasks"
                :key="task.id"
                class="task-item"
                :class="{ 'task-overdue': isTaskOverdue(task) }"
              >
                <div class="task-priority">
                  <el-icon v-if="isTaskOverdue(task)" class="overdue-icon"
                    ><Warning
                  /></el-icon>
                </div>

                <div class="task-content">
                  <div class="task-header">
                    <div
                      class="task-description"
                      v-html="task.description"
                    ></div>
                    <el-tag :type="getTaskStatusType(task.status)" size="small">
                      {{ getTaskStatusText(task.status) }}
                    </el-tag>
                  </div>

                  <div class="task-meta">
                    <div class="meta-item">
                      <el-icon><User /></el-icon>
                      <span>{{ task.assignedToName }}</span>
                    </div>
                    <div class="meta-item">
                      <el-icon><Calendar /></el-icon>
                      <span
                        >{{ formatDate(task.beginDate) }} -
                        {{ formatDate(task.dueDate) }}</span
                      >
                    </div>
                    <div v-if="task.actualEndDate" class="meta-item completed">
                      <el-icon><Check /></el-icon>
                      <span>完成于 {{ formatDate(task.actualEndDate) }}</span>
                    </div>
                  </div>
                </div>

                <div class="task-actions">
                  <el-button type="text" size="small" @click="editTask(task)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDeleteTask(task)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 右侧：项目成员和文档 -->
        <div class="right-content">
          <!-- 项目成员 -->
          <el-card class="members-card">
            <template #header>
              <div class="card-header">
                <span>项目成员</span>
                <el-button
                  type="primary"
                  size="small"
                  @click="$router.push(`/projects/${project.id}/members`)"
                >
                  <el-icon><User /></el-icon>
                  管理
                </el-button>
              </div>
            </template>

            <div
              v-if="!project.members || project.members.length === 0"
              class="empty-state"
            >
              <el-empty description="暂无成员" :image-size="80">
                <el-button
                  type="primary"
                  size="small"
                  @click="$router.push(`/projects/${project.id}/members`)"
                >
                  添加成员
                </el-button>
              </el-empty>
            </div>

            <div v-else class="members-list">
              <div
                v-for="member in project.members"
                :key="member.userId"
                class="member-card"
                :title="`${member.name || '未知用户'} - ${getRoleText(
                  member.role
                )}`"
                @click="viewMemberDetail(member)"
              >
                <div class="member-avatar">
                  <el-avatar :size="40">
                    {{ member.name?.charAt(0) || "U" }}
                  </el-avatar>
                </div>
                <div
                  v-if="member.role"
                  class="role-badge"
                  :class="`role-${member.role}`"
                >
                  {{ getRoleText(member.role) }}
                </div>
                <div class="member-name">{{ member.name || "未知用户" }}</div>
                <div class="member-account">{{ member.account || "" }}</div>
              </div>
            </div>
          </el-card>

          <!-- 项目文档 -->
          <el-card class="docs-card">
            <template #header>
              <div class="card-header">
                <span>项目文档</span>
                <div class="header-actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click="showCreateDocDialog = true"
                  >
                    <el-icon><Plus /></el-icon>
                    新建
                  </el-button>
                </div>
              </div>
            </template>

            <div v-if="docsLoading" class="loading-container">
              <el-skeleton :rows="3" animated />
            </div>

            <div v-else-if="projectDocs.length === 0" class="empty-state">
              <el-empty description="暂无文档" :image-size="60">
                <el-button
                  type="primary"
                  size="small"
                  @click="showCreateDocDialog = true"
                >
                  创建第一个文档
                </el-button>
              </el-empty>
            </div>

            <div v-else class="docs-list">
              <div
                v-for="doc in projectDocs"
                :key="doc.id"
                class="doc-item"
                @click="viewDoc(doc)"
              >
                <div class="doc-icon">
                  <el-icon v-if="doc.type === 'file'"><Document /></el-icon>
                  <el-icon v-else><EditPen /></el-icon>
                </div>
                <div class="doc-info">
                  <div class="doc-title">{{ doc.title }}</div>
                  <div class="doc-meta">
                    <span class="doc-type">{{
                      doc.type === "file" ? "文件" : "文档"
                    }}</span>
                    <span class="doc-date">{{
                      formatDate(doc.createdAt)
                    }}</span>
                  </div>
                  <div v-if="doc.tags && doc.tags.length > 0" class="doc-tags">
                    <el-tag
                      v-for="tag in doc.tags"
                      :key="tag"
                      size="small"
                      type="info"
                      class="tag-item"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
                <div class="doc-actions" @click.stop>
                  <el-button type="text" size="small" @click="editDoc(doc)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button type="text" size="small" @click="deleteDoc(doc)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 编辑项目对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑项目"
      width="600px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入项目描述"
          />
        </el-form-item>
        <el-form-item label="项目状态">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="进行中" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="editForm.startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="editForm.endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleEditSubmit"
        >
          {{ submitting ? "保存中..." : "保存" }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 创建/编辑任务对话框 -->
    <TaskForm
      v-model="showCreateTaskDialog"
      :project-id="projectId"
      :task-data="editingTask"
      @success="handleTaskSubmit"
    />

    <!-- 创建/编辑文档对话框 -->
    <el-dialog
      v-model="showCreateDocDialog"
      :title="editingDoc ? '编辑文档' : '新建文档'"
      width="800px"
      @close="resetDocForm"
    >
      <el-form
        ref="docFormRef"
        :model="docForm"
        :rules="docRules"
        label-width="80px"
      >
        <el-form-item label="文档类型" prop="type">
          <el-radio-group v-model="docForm.type" @change="onDocTypeChange">
            <el-radio label="rich">富文本文档</el-radio>
            <el-radio label="file">文件上传</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="文档标题" prop="title">
          <el-input v-model="docForm.title" placeholder="请输入文档标题" />
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="docForm.tags"
            multiple
            filterable
            allow-create
            placeholder="选择或创建标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>

        <!-- 富文本编辑器 -->
        <el-form-item
          v-if="docForm.type === 'rich'"
          label="文档内容"
          prop="content"
        >
          <div class="rich-editor">
            <div ref="editorRef" style="height: 300px"></div>
          </div>
        </el-form-item>

        <!-- 文件上传 -->
        <el-form-item
          v-if="docForm.type === 'file'"
          label="选择文件"
          prop="file"
        >
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :show-file-list="false"
            accept=".pdf,.doc,.docx,.txt,.md,.xlsx,.xls,.ppt,.pptx"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              选择文件
            </el-button>
          </el-upload>
          <div v-if="docForm.file" class="file-info">
            <el-icon><Document /></el-icon>
            <span>{{ docForm.file.name }}</span>
            <span class="file-size"
              >({{ formatFileSize(docForm.file.size) }})</span
            >
          </div>
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="docForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入文档描述（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showCreateDocDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="docSubmitting"
          @click="handleDocSubmit"
        >
          {{ docSubmitting ? "保存中..." : "保存" }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 文档查看对话框 -->
    <el-dialog
      v-model="showViewDocDialog"
      :title="viewingDoc?.title"
      width="900px"
      @close="viewingDoc = null"
    >
      <div v-if="viewingDoc" class="doc-viewer">
        <div v-if="viewingDoc.type === 'file'" class="file-viewer">
          <div class="file-info">
            <el-icon><Document /></el-icon>
            <span>{{ viewingDoc.title }}</span>
            <el-button
              type="primary"
              size="small"
              @click="downloadFile(viewingDoc)"
            >
              <el-icon><Download /></el-icon>
              下载
            </el-button>
          </div>
          <div
            v-if="viewingDoc.tags && viewingDoc.tags.length > 0"
            class="doc-tags"
          >
            <el-tag
              v-for="tag in viewingDoc.tags"
              :key="tag"
              size="small"
              type="info"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
        <div v-else class="rich-content" v-html="viewingDoc.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import TaskForm from "@/components/TaskForm.vue";
import { useRoute } from "vue-router";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import {
  getProjectInfo,
  updateProject,
  type Project,
  type UpdateProjectRequest,
} from "@/api/project";
import { getTaskList, deleteTask, type ProjectTask } from "@/api/task";
import { getProjectMembers } from "@/api/projectMember";

import dayjs from "dayjs";

const route = useRoute();

const projectId = computed(() => parseInt(route.params.id as string));

const loading = ref(false);
const tasksLoading = ref(false);
const submitting = ref(false);
const showEditDialog = ref(false);
const showCreateTaskDialog = ref(false);

const project = ref<Project | null>(null);
const tasks = ref<ProjectTask[]>([]);
const editingTask = ref<ProjectTask | null>(null);

// 任务筛选
const taskSearchKeyword = ref("");
const taskStatusFilter = ref("");

// 文档相关
const docsLoading = ref(false);
const docSubmitting = ref(false);
const showCreateDocDialog = ref(false);
const showViewDocDialog = ref(false);
const projectDocs = ref<any[]>([]);
const editingDoc = ref<any>(null);
const viewingDoc = ref<any>(null);
const editorRef = ref();
const uploadRef = ref();

const stats = reactive({
  totalTasks: 0,
  completedTasks: 0,
  pendingTasks: 0,
  overdueTasks: 0,
});

const editFormRef = ref<FormInstance>();
const editForm = reactive({
  name: "",
  description: "",
  status: 0,
  startDate: "",
  endDate: "",
});

const editRules: FormRules = {
  name: [
    { required: true, message: "请输入项目名称", trigger: "blur" },
    { max: 50, message: "项目名称不能超过50个字符", trigger: "blur" },
  ],
};

const docFormRef = ref<FormInstance>();
const docForm = reactive({
  type: "rich",
  title: "",
  content: "",
  tags: [],
  description: "",
  file: null as File | null,
});

const docRules: FormRules = {
  title: [
    { required: true, message: "请输入文档标题", trigger: "blur" },
    { max: 100, message: "文档标题不能超过100个字符", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择文档类型", trigger: "change" }],
};

// 可用标签
const availableTags = ref([
  "需求文档",
  "设计文档",
  "技术文档",
  "测试文档",
  "用户手册",
  "API文档",
  "会议记录",
  "其他",
]);

const fetchProject = async () => {
  loading.value = true;
  try {
    const result = await getProjectInfo(projectId.value);
    const foundProject = result.data;
    if (foundProject) {
      project.value = foundProject;
      editForm.name = foundProject.name;
      editForm.description = foundProject.description || "";
      editForm.status = foundProject.status;
      editForm.startDate = foundProject.startDate || "";
      editForm.endDate = foundProject.endDate || "";
      const memberRes = await getProjectMembers(projectId.value);
      project.value.members = memberRes.data;
    }
  } catch (error) {
    ElMessage.error("获取项目信息失败");
  } finally {
    loading.value = false;
  }
};

const fetchTasks = async () => {
  tasksLoading.value = true;
  try {
    const result = await getTaskList({
      projectId: projectId.value,
      pageDto: { pageNumber: 1, pageSize: 100 },
    });
    tasks.value = result.data.items;

    // 计算统计数据
    stats.totalTasks = result.data.items.length;
    stats.completedTasks = result.data.items.filter(
      (task) => task.status === 1
    ).length;
    stats.pendingTasks = result.data.items.filter(
      (task) => task.status === 0
    ).length;
    stats.overdueTasks = result.data.items.filter(
      (task) => task.status === 0 && dayjs(task.dueDate).isBefore(dayjs())
    ).length;
  } catch (error) {
    ElMessage.error("获取任务列表失败");
  } finally {
    tasksLoading.value = false;
  }
};

const fetchDocs = async () => {
  docsLoading.value = true;
  try {
    // 模拟获取文档列表
    // 实际项目中应该调用API
    projectDocs.value = [
      {
        id: 1,
        title: "项目需求文档",
        type: "rich",
        content: "<h1>项目需求</h1><p>这是项目需求文档的内容...</p>",
        tags: ["需求文档", "重要"],
        description: "项目核心需求说明",
        createdAt: "2024-01-15",
        updatedAt: "2024-01-15",
      },
      {
        id: 2,
        title: "技术架构设计.pdf",
        type: "file",
        fileUrl: "/files/tech-arch.pdf",
        tags: ["技术文档", "设计文档"],
        description: "系统技术架构设计文档",
        createdAt: "2024-01-10",
        updatedAt: "2024-01-10",
      },
    ];
  } catch (error) {
    ElMessage.error("获取文档列表失败");
  } finally {
    docsLoading.value = false;
  }
};

const resetEditForm = () => {
  if (project.value) {
    editForm.name = project.value.name;
    editForm.description = project.value.description || "";
    editForm.status = project.value.status;
    editForm.startDate = project.value.startDate || "";
    editForm.endDate = project.value.endDate || "";
  }
  editFormRef.value?.resetFields();
};

const resetDocForm = () => {
  editingDoc.value = null;
  docForm.type = "rich";
  docForm.title = "";
  docForm.content = "";
  docForm.tags = [];
  docForm.description = "";
  docForm.file = null;
  docFormRef.value?.resetFields();
};

const onDocTypeChange = () => {
  docForm.content = "";
  docForm.file = null;
};

const handleFileChange = (file: any) => {
  docForm.file = file.raw;
};

const beforeUpload = (file: File) => {
  const isValidType = /\.(pdf|doc|docx|txt|md|xlsx|xls|ppt|pptx)$/i.test(
    file.name
  );
  if (!isValidType) {
    ElMessage.error("只支持 PDF、Word、Excel、PowerPoint、文本文件格式!");
    return false;
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error("文件大小不能超过 10MB!");
    return false;
  }
  return false; // 阻止自动上传
};

const formatFileSize = (size: number) => {
  if (size < 1024) return size + " B";
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + " KB";
  return (size / (1024 * 1024)).toFixed(1) + " MB";
};

const viewDoc = (doc: any) => {
  viewingDoc.value = doc;
  showViewDocDialog.value = true;
};

const editDoc = (doc: any) => {
  editingDoc.value = doc;
  docForm.type = doc.type;
  docForm.title = doc.title;
  docForm.content = doc.content || "";
  docForm.tags = doc.tags || [];
  docForm.description = doc.description || "";
  showCreateDocDialog.value = true;
};

const deleteDoc = async (doc: any) => {
  try {
    await ElMessageBox.confirm("确定要删除这个文档吗？", "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // 实际项目中应该调用删除API
    projectDocs.value = projectDocs.value.filter((d) => d.id !== doc.id);
    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const downloadFile = (doc: any) => {
  // 实际项目中应该处理文件下载
  ElMessage.info(`下载文件: ${doc.title}`);
};

const viewMemberDetail = (member: any) => {
  ElMessage.info(`查看成员详情: ${member.name}`);
  // 这里可以打开成员详情对话框或跳转到成员详情页面
};

const handleDocSubmit = async () => {
  if (!docFormRef.value) return;

  try {
    const valid = await docFormRef.value.validate();
    if (!valid) return;

    docSubmitting.value = true;

    if (editingDoc.value) {
      // 更新文档
      const index = projectDocs.value.findIndex(
        (d) => d.id === editingDoc.value.id
      );
      if (index !== -1) {
        projectDocs.value[index] = {
          ...projectDocs.value[index],
          title: docForm.title,
          content: docForm.content,
          tags: docForm.tags,
          description: docForm.description,
          updatedAt: dayjs().format("YYYY-MM-DD"),
        };
      }
      ElMessage.success("更新成功");
    } else {
      // 创建文档
      const newDoc = {
        id: Date.now(),
        title: docForm.title,
        type: docForm.type,
        content: docForm.content,
        tags: docForm.tags,
        description: docForm.description,
        createdAt: dayjs().format("YYYY-MM-DD"),
        updatedAt: dayjs().format("YYYY-MM-DD"),
      };
      projectDocs.value.unshift(newDoc);
      ElMessage.success("创建成功");
    }

    showCreateDocDialog.value = false;
  } catch (error) {
    ElMessage.error(editingDoc.value ? "更新失败" : "创建失败");
  } finally {
    docSubmitting.value = false;
  }
};

const handleEditSubmit = async () => {
  if (!editFormRef.value || !project.value) return;

  try {
    const valid = await editFormRef.value.validate();
    if (!valid) return;

    submitting.value = true;

    const updateData: UpdateProjectRequest = {
      id: project.value.id,
      name: editForm.name,
      description: editForm.description,
      status: editForm.status,
      startDate: editForm.startDate,
      endDate: editForm.endDate,
    };

    await updateProject(updateData);
    ElMessage.success("更新成功");
    showEditDialog.value = false;
    fetchProject();
  } catch (error) {
    ElMessage.error("更新失败");
  } finally {
    submitting.value = false;
  }
};

const editTask = (task: ProjectTask) => {
  editingTask.value = task;
  showCreateTaskDialog.value = true;
};

const handleDeleteTask = async (task: ProjectTask) => {
  try {
    await ElMessageBox.confirm("确定要删除这个任务吗？", "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await deleteTask(task.id);
    ElMessage.success("删除成功");
    fetchTasks();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const handleTaskSubmit = async () => {
  await fetchTasks();
};

const getStatusType = (status: number) => {
  return status === 1 ? "success" : "warning";
};

const getStatusText = (status: number) => {
  return status === 1 ? "已完成" : "进行中";
};

const getTaskStatusType = (status: number) => {
  return status === 1 ? "success" : "warning";
};

const getTaskStatusText = (status: number) => {
  return status === 1 ? "已完成" : "进行中";
};

const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    owner: "项目负责人",
    developer: "开发人员",
    tester: "测试人员",
    member: "成员",
    observer: "观察者",
  };
  return roleMap[role] || role;
};

// 筛选后的任务列表
const filteredTasks = computed(() => {
  let result = tasks.value;

  // 按关键词筛选
  if (taskSearchKeyword.value) {
    result = result.filter(
      (task) =>
        task.description
          .toLowerCase()
          .includes(taskSearchKeyword.value.toLowerCase()) ||
        task.assignedToName
          .toLowerCase()
          .includes(taskSearchKeyword.value.toLowerCase())
    );
  }

  // 按状态筛选
  if (taskStatusFilter.value !== "") {
    result = result.filter(
      (task) => task.status === Number(taskStatusFilter.value)
    );
  }

  return result;
});

const isTaskOverdue = (task: ProjectTask) => {
  return task.status === 0 && dayjs(task.dueDate).isBefore(dayjs());
};

const formatDate = (date: string | undefined) => {
  if (!date) return "未设置";
  return dayjs(date).format("YYYY-MM-DD");
};

onMounted(() => {
  fetchProject();
  fetchTasks();
  fetchDocs();
});
</script>

<style scoped lang="scss">
.project-detail {
  .loading-container {
    padding: 40px 0;
  }

  .empty-state {
    padding: 60px 0;
  }

  .project-header-card {
    margin-bottom: 24px;

    .project-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .header-left {
        flex: 1;

        h1 {
          font-size: 28px;
          color: #333;
          margin-bottom: 8px;
        }

        p {
          color: #666;
          font-size: 16px;
          margin-bottom: 16px;
        }

        .project-meta {
          display: flex;
          align-items: center;
          gap: 16px;

          .meta-item {
            display: flex;
            align-items: center;
            color: #666;
            font-size: 14px;

            .el-icon {
              margin-right: 4px;
            }
          }
        }
      }
    }
  }

  .main-content {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 24px;
    margin-bottom: 24px;

    .left-content {
      min-width: 0; // 防止网格溢出
    }

    .right-content {
      min-width: 0;
    }
  }

  .stats-card {
    margin-bottom: 24px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16px;

      .stat-item {
        display: flex;
        align-items: center;
        padding: 16px;
        background: #f8f9fa;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          background: #e9ecef;
          transform: translateY(-2px);
        }

        .stat-icon {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
          font-size: 18px;
          color: white;

          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }

          &.completed {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }

          &.pending {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }

          &.overdue {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
        }

        .stat-info {
          .stat-number {
            font-size: 20px;
            font-weight: bold;
            color: #333;
            line-height: 1;
          }

          .stat-label {
            color: #666;
            font-size: 12px;
            margin-top: 4px;
          }
        }
      }
    }
  }

  .tasks-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-actions {
        display: flex;
        align-items: center;
      }
    }

    .loading-container {
      padding: 20px 0;
    }

    .empty-state {
      padding: 40px 0;
    }

    .task-list {
      .task-item {
        display: flex;
        align-items: flex-start;
        padding: 16px 0;
        border-bottom: 1px solid #f0f0f0;
        transition: all 0.3s ease;
        gap: 12px;

        &:last-child {
          border-bottom: none;
        }

        &.task-overdue {
          background: #fff2f0;
          border-left: 4px solid #ff4d4f;
          padding-left: 12px;
        }

        .task-priority {
          width: 24px;
          flex-shrink: 0; // 防止图标被压缩
          margin-top: 2px; // 与任务描述对齐

          .overdue-icon {
            color: #ff4d4f;
            font-size: 16px;
          }
        }

        .task-content {
          flex: 1;
          min-width: 0; // 允许内容收缩

          .task-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 8px;
            gap: 12px;

            .task-description {
              flex: 1;
              min-width: 0;
            }
          }

          .task-meta {
            display: flex;
            align-items: center;
            gap: 16px;
            flex-wrap: wrap;

            .meta-item {
              display: flex;
              align-items: center;
              color: #666;
              font-size: 14px;

              &.completed {
                color: #52c41a;
              }

              .el-icon {
                margin-right: 4px;
              }
            }
          }
        }

        .task-actions {
          display: flex;
          gap: 4px;
          margin-left: 12px;
          flex-shrink: 0; // 防止按钮被压缩
          margin-top: 2px; // 与任务描述对齐
        }
      }
    }
  }

  .members-card {
    margin-bottom: 16px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .empty-state {
      padding: 20px 0;
    }

    .members-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
      gap: 16px;
      padding: 8px 0;

      .member-card {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 12px 8px;
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-radius: 16px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        cursor: pointer;
        position: relative;
        border: 1px solid rgba(0, 0, 0, 0.05);

        &:hover {
          background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
          transform: translateY(-3px) scale(1.02);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
          border-color: rgba(0, 0, 0, 0.1);

          .role-badge {
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
            top: -6px;
            right: -6px;
          }
        }

        &:active {
          transform: translateY(-1px) scale(0.98);
        }

        .member-avatar {
          margin-bottom: 8px;
        }

        .role-badge {
          position: absolute;
          top: -4px;
          right: -4px;
          padding: 3px 8px;
          border-radius: 10px;
          font-size: 9px;
          font-weight: bold;
          color: white;
          white-space: nowrap;
          transition: all 0.3s ease;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
          z-index: 2;
          border: 1px solid rgba(255, 255, 255, 0.3);
          backdrop-filter: blur(4px);

          &.role-owner {
            background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
          }

          &.role-developer {
            background: linear-gradient(135deg, #fa8c16 0%, #ffa940 100%);
          }

          &.role-tester {
            background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
          }

          &.role-member {
            background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
          }

          &.role-observer {
            background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);
          }

          // 为重要角色添加脉冲动画
          &.role-owner {
            animation: pulse-owner 2s infinite;
          }

          &.role-developer {
            animation: pulse-developer 2s infinite;
          }
        }

        // 脉冲动画
        @keyframes pulse-owner {
          0% {
            box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
          }
          50% {
            box-shadow: 0 2px 8px rgba(255, 77, 79, 0.6),
              0 0 0 4px rgba(255, 77, 79, 0.1);
          }
          100% {
            box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
          }
        }

        @keyframes pulse-developer {
          0% {
            box-shadow: 0 2px 8px rgba(250, 140, 22, 0.3);
          }
          50% {
            box-shadow: 0 2px 8px rgba(250, 140, 22, 0.6),
              0 0 0 4px rgba(250, 140, 22, 0.1);
          }
          100% {
            box-shadow: 0 2px 8px rgba(250, 140, 22, 0.3);
          }
        }

        .member-name {
          font-size: 12px;
          font-weight: 500;
          color: #333;
          text-align: center;
          margin-bottom: 2px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
        }

        .member-account {
          font-size: 10px;
          color: #666;
          text-align: center;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
        }
      }
    }
  }

  .docs-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-actions {
        display: flex;
        gap: 8px;
      }
    }

    .empty-state {
      padding: 20px 0;
    }

    .loading-container {
      padding: 20px 0;
    }

    .docs-list {
      .doc-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: all 0.3s ease;

        &:last-child {
          border-bottom: none;
        }

        &:hover {
          background: #f8f9fa;
          border-radius: 4px;
          padding-left: 8px;
          padding-right: 8px;
        }

        .doc-icon {
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f0f2f5;
          border-radius: 6px;
          margin-right: 12px;
          color: #666;
          font-size: 16px;
        }

        .doc-info {
          flex: 1;
          min-width: 0;

          .doc-title {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .doc-meta {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 4px;

            .doc-type {
              font-size: 11px;
              color: #999;
              background: #f0f0f0;
              padding: 2px 6px;
              border-radius: 3px;
            }

            .doc-date {
              font-size: 11px;
              color: #999;
            }
          }

          .doc-tags {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;

            .tag-item {
              font-size: 10px;
            }
          }
        }

        .doc-actions {
          display: flex;
          gap: 4px;
          opacity: 0;
          transition: opacity 0.3s ease;
        }

        &:hover .doc-actions {
          opacity: 1;
        }
      }
    }
  }

  .tasks-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .loading-container {
      padding: 20px 0;
    }

    .empty-state {
      padding: 40px 0;
    }

    .task-list {
      .task-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .task-content {
          flex: 1;

          .task-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;

            h4 {
              font-size: 16px;
              color: #333;
              margin: 0;
            }
          }

          .task-meta {
            display: flex;
            align-items: center;
            gap: 16px;

            .meta-item {
              display: flex;
              align-items: center;
              color: #666;
              font-size: 14px;

              .el-icon {
                margin-right: 4px;
              }
            }
          }
        }

        .task-actions {
          display: flex;
          gap: 8px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .project-detail {
    .project-header {
      flex-direction: column;
      gap: 16px;

      .header-right {
        width: 100%;

        .el-button-group {
          width: 100%;

          .el-button {
            flex: 1;
          }
        }
      }
    }

    .main-content {
      grid-template-columns: 1fr;
      gap: 16px;

      .right-content {
        order: -1; // 在移动端将成员卡片放在前面
      }
    }

    .stats-card {
      .stats-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;

        .stat-item {
          padding: 12px;

          .stat-icon {
            width: 32px;
            height: 32px;
            font-size: 14px;
          }

          .stat-info {
            .stat-number {
              font-size: 16px;
            }

            .stat-label {
              font-size: 10px;
            }
          }
        }
      }
    }

    .tasks-card {
      .card-header {
        flex-direction: column;
        gap: 12px;
        align-items: stretch;

        .header-actions {
          justify-content: space-between;

          .el-input {
            width: 120px !important;
          }

          .el-select {
            width: 100px !important;
          }
        }
      }

      .task-list {
        .task-item {
          padding: 12px 0;
          gap: 8px;

          .task-content {
            .task-header {
              flex-direction: column;
              align-items: flex-start;
              gap: 8px;

              .task-description {
                width: 100%;
                font-size: 14px;
              }
            }

            .task-meta {
              gap: 8px;

              .meta-item {
                font-size: 12px;
              }
            }
          }
        }
      }
    }

    .members-card {
      .members-list {
        grid-template-columns: repeat(auto-fill, minmax(70px, 1fr));
        gap: 12px;

        .member-card {
          padding: 8px 6px;

          .member-avatar {
            .el-avatar {
              width: 32px !important;
              height: 32px !important;
            }
          }

          .role-badge {
            top: -3px;
            right: -3px;
            padding: 1px 4px;
            font-size: 8px;
            border-radius: 6px;
          }

          .member-name {
            font-size: 11px;
          }

          .member-account {
            font-size: 9px;
          }
        }
      }
    }

    .docs-card {
      .docs-list {
        .doc-item {
          padding: 8px 0;

          .doc-icon {
            width: 28px;
            height: 28px;
            font-size: 14px;
          }

          .doc-info {
            .doc-title {
              font-size: 13px;
            }

            .doc-meta {
              .doc-type {
                font-size: 10px;
              }

              .doc-date {
                font-size: 10px;
              }
            }

            .doc-tags {
              .tag-item {
                font-size: 9px;
              }
            }
          }
        }
      }
    }
  }
}

// 对话框样式
.rich-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;

  .ql-toolbar {
    border-bottom: 1px solid #dcdfe6;
  }

  .ql-container {
    border: none;
  }
}

// Markdown编辑器样式
.markdown-editor {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
  background: #fff;

  .editor-tabs {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    background: #f8f9fa;
    border-bottom: 1px solid #e4e7ed;

    .markdown-tips {
      color: #909399;
      cursor: help;
      font-size: 14px;

      &:hover {
        color: #409eff;
      }
    }
  }

  .editor-content {
    padding: 12px;

    .markdown-textarea {
      .el-textarea__inner {
        border: none;
        resize: vertical;
        font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
        font-size: 14px;
        line-height: 1.5;
      }
    }
  }

  .preview-content {
    padding: 12px;
    min-height: 120px;
    background: #fff;
    border: none;
    font-size: 14px;
    line-height: 1.6;

    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
      margin: 16px 0 8px 0;
      font-weight: 600;
      color: #333;
    }

    h1 {
      font-size: 20px;
    }
    h2 {
      font-size: 18px;
    }
    h3 {
      font-size: 16px;
    }

    p {
      margin: 8px 0;
    }

    ul,
    ol {
      margin: 8px 0;
      padding-left: 20px;
    }

    li {
      margin: 4px 0;
    }

    code {
      background: #f1f3f4;
      padding: 2px 4px;
      border-radius: 3px;
      font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
      font-size: 13px;
    }

    pre {
      background: #f8f9fa;
      padding: 12px;
      border-radius: 4px;
      overflow-x: auto;
      margin: 8px 0;

      code {
        background: none;
        padding: 0;
      }
    }

    a {
      color: #1890ff;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }

    strong {
      font-weight: 600;
    }

    em {
      font-style: italic;
    }
  }
}

// 任务描述样式
.task-description {
  flex: 1;
  font-size: 16px;
  color: #333;
  line-height: 1.5;
  min-width: 0; // 允许内容收缩
  max-width: none; // 移除最大宽度限制
  word-wrap: break-word; // 长单词换行
  overflow-wrap: break-word; // 现代浏览器的换行
  word-break: break-word; // 强制换行

  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    margin: 8px 0 4px 0;
    font-weight: 600;
    color: #333;
  }

  h1 {
    font-size: 18px;
  }
  h2 {
    font-size: 16px;
  }
  h3 {
    font-size: 15px;
  }

  p {
    margin: 4px 0;
  }

  ul,
  ol {
    margin: 4px 0;
    padding-left: 16px;
  }

  li {
    margin: 2px 0;
  }

  code {
    background: #f1f3f4;
    padding: 1px 3px;
    border-radius: 2px;
    font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
    font-size: 12px;
  }

  pre {
    background: #f8f9fa;
    padding: 8px;
    border-radius: 3px;
    overflow-x: auto;
    margin: 4px 0;

    code {
      background: none;
      padding: 0;
    }
  }

  a {
    color: #1890ff;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  strong {
    font-weight: 600;
  }

  em {
    font-style: italic;
  }
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 14px;
  color: #666;

  .file-size {
    color: #999;
    font-size: 12px;
  }
}

.doc-viewer {
  .file-viewer {
    .file-info {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 8px;
      margin-bottom: 16px;

      .el-icon {
        font-size: 24px;
        color: #666;
      }

      span {
        flex: 1;
        font-size: 16px;
        font-weight: 500;
      }
    }

    .doc-tags {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;

      .tag-item {
        font-size: 12px;
      }
    }
  }

  .rich-content {
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    min-height: 200px;

    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
      margin-top: 0;
      margin-bottom: 16px;
    }

    p {
      margin-bottom: 12px;
      line-height: 1.6;
    }

    ul,
    ol {
      margin-bottom: 12px;
      padding-left: 20px;
    }

    li {
      margin-bottom: 4px;
    }
  }
}
</style>


